use crate::datasource::RelationCondition;

use super::{ClassRelation, RelationDirection};

pub trait ClassRelationGetter {
    fn class_relations() -> anyhow::Result<Vec<ClassRelation>> {
        Ok(vec![])
    }
    fn class_relations_by_condition(
        condition: &RelationCondition,
    ) -> anyhow::Result<Vec<ClassRelation>> {
        let mut relations = Self::class_relations()?;
        //relation_identifier
        if let Some(relation_identifier) = &condition.relation_identifier {
            relations = relations
                .iter()
                .filter(|r| r.relation_identifier == *relation_identifier)
                .map(|v| v.clone())
                .collect();
        }

        //related_type
        if let Some(related_type) = &condition.related_type {
            relations = relations
                .iter()
                .filter(|r| r.related_type == *related_type)
                .map(|v| v.clone())
                .collect();
        }
        //related_at
        if let Some(related_at) = &condition.related_at {
            relations = relations
                .iter()
                .filter(|r| r.related_at == *related_at)
                .map(|v| v.clone())
                .collect();
        }
        //
        if let Some(other) = &condition.class_identifier {
            if let Some(direction) = &condition.direction {
                match direction {
                    RelationDirection::Obverse => {
                        relations = relations
                            .iter()
                            .filter(|r| r.src_identifier == *other)
                            .map(|v| v.clone())
                            .collect();
                    }
                    RelationDirection::Reverse => {
                        relations = relations
                            .iter()
                            .filter(|r| r.target_identifier == *other)
                            .map(|v| v.clone())
                            .collect();
                    }
                }
            } else {
                //没有方向
                relations = relations
                    .iter()
                    .filter(|r| r.src_identifier == *other || r.target_identifier == *other)
                    .map(|v| v.clone())
                    .collect();
            }
        }
        Ok(relations)
    }
}
